import json
import os
import re
import time

import requests

from AIGCReport.report_templates.ExportReport import ExportAIGCReport
from ExportDocumentReport.ExportReport import ExportReport as ExportLayuiReport
from config.setting import ReportDir
from libs.helper import get_token
from libs.tools import Notification
from models import user
from models.aigc_order_info import AigcOrderInfo
# from models.AigcReportInfo import AigcOrderInfo
from models.aigc_paragraphs import AigcParagraphs
from models.document_dom import DocumentDom
from models.orders_info import orders_info
from models.RedisOperation import RedisClient
from models.base import db, session_scope, shutdown_session
from models.captcha import captcha
from models.orders import Orders
from models.report_info import report_info
from models.report_source_info import report_source_info
from models.sentence import Sentence
from models.sentence_detail import sentence_detail
from models.sentence_word import SentenceWord
from models.taobao_orders import taobao_orders
from models.user import User
from oss.alioss import AliOss
from taobao_api.update_order_status import Logistics_Dummy_Send


class MakeAIGCReport(object):

    def __init__(self):
        self.r = RedisClient()

    def checkAIGC(self, order_number):
        with session_scope() as session:
            aigcParagraphs = session.query(AigcParagraphs).filter(AigcParagraphs.order_number == order_number).filter(
                AigcParagraphs.type == 'content').all()
            for aigcParagraph in aigcParagraphs:
                if len(aigcParagraph.content) > 100:
                    aigc = self.aigc(aigcParagraph.content)
                    print(aigc)
                    if aigc['predict'] == 'ChatGPT':
                        session.query(AigcParagraphs).filter(AigcParagraphs.id == aigcParagraph.id).update({
                            'ai': 1,
                            'rate': round(float(aigc['score']), 2)
                        })

    def aigc(self, content):
        headers = {'content-type': 'application/json'}
        data = {
            'sentence': content
        }
        aiResult = {'predict': 'Human'}
        try:
            aigcRes = requests.post('http://111.173.89.215:5003/data', headers=headers, data=json.dumps(data))
            if aigcRes.status_code == 200:
                print(aigcRes)
                aiResult = json.loads(aigcRes.text)
                return aiResult
            return aiResult
        except Exception as e:
            print(e)
            return aiResult

    def base_info(self, order_number):
        aigcParagraphs = db.query(AigcParagraphs).filter(AigcParagraphs.order_number == order_number).all()
        aigcInfo = db.query(AigcOrderInfo).filter(AigcOrderInfo.order_number == order_number).first()
        charSum = aigcInfo.chars_sum
        sliceSum = len(aigcParagraphs)
        author = aigcInfo.author
        check_time = aigcInfo.create_datetime
        title = aigcInfo.title
        rate = self.caculateRate(aigcParagraphs)
        return {
            'title': title,
            'author': author,
            'slice_sum': sliceSum,
            'char_sum': charSum,
            'submit_time': check_time,
            'rate': rate,
            'paragraphs': aigcParagraphs
        }

    def getCharssum(self, aigcParagraphs):
        count = 0
        for item in aigcParagraphs:
            count += len(item['content'])
        return count

    def caculateRate(self, aigcParagraphs):
        total = 0
        ai_count = 0
        for item in aigcParagraphs:
            if item.type in ['content']:
                total += len(item.content)
                if item.ai == 1:
                    ai_count += len(item.content)
        total_rate = 0 if ai_count == 0 else round(ai_count*100 / total, 2)
        return total_rate

    def create_ScatterDiagram(self, report, order_number):
        similar_sentence = sentence_detail()
        sentence = SentenceWord()
        max_x = sentence.sentence_count(order_number)
        orange_data, red_data = similar_sentence.top_rate(order_number)
        report.create_ScatterDiagram(orange_data, red_data, max_x)

    def update_captcha(self, base_info):
        with session_scope() as session:
            captcha_model = captcha()
            captcha_model.captcha_number = base_info['captcha']
            captcha_model.title = base_info['title']
            captcha_model.author = base_info['author']
            captcha_model.char_sum = base_info['char_sum']
            captcha_model.create_time = base_info['submit_time']
            captcha_model.similar_rate = base_info['except_author_rate']
            session.add(captcha_model)
            session.commit()

    def paragraph_codebar(self, order_number):
        results = db.query(AigcParagraphs).filter_by(order_number=order_number).all()
        codebar = []
        for item in results:
            if item.ai == 1:
                codebar.append(2)
            else:
                codebar.append(0)
        return [codebar]

    def create_barcode(self, report, order_number):
        report.create_barcode(self.paragraph_codebar(order_number))

    # def create_simple_pdf_html(self, report, order_number, base_info):
    #     similar_sentence = sentence_detail()
    #     internet, local = similar_sentence.internetData(order_number)
    #     report.create_simple_pdf_html(local=local, internet=internet, view_info=base_info)

    # def create_report_html(self, report, base_info):
    #     report.create_report_html(base_info)

    def create_pdf_html(self, report, base_info, order_number):
        pdfname = report.create_pdf_html(base_info)
        with session_scope() as session:
            session.query(AigcOrderInfo).filter(AigcOrderInfo.order_number == order_number).update(
                {'completed': 1, 'rate': base_info['rate'], 'pdfname': pdfname})
            session.commit()

    def run(self):
        while True:
            order_number = self.r.get_order_number
            print(order_number)
            if order_number:
                self.makeAigcReport(order_number)
            else:
                print('sleep 5 seconds...')
                time.sleep(3)

    def logistics(self, order_number):
        shop_token = {
            'samereport教育旗舰店': 'TbAldszyw2zfa35ttemzxhbh2zkx27x6mabxssreswt2vkxgxt',
            '正才教育专营店': 'TbAldsa4hc3vsabbpebnyypp43g5n8yss9kpuyyx4yct7w68z5',
        }
        order_numbers = db.query(AigcOrderInfo).filter_by(order_number=order_number).all()
        for order in order_numbers:
            shop_info = db.query(taobao_orders).filter_by(order_number=order.taobao_orders).first()
            if shop_info:
                if shop_info.order_number in ['839843905366842610', '836876003067671953']:
                    return False
                shop_name = shop_info.shop
                if shop_name in list(shop_token.keys()):
                    token = shop_token[shop_name]
                    tids = []
                    for item in order_numbers:
                        tids.append(item.taobao_orders)
                    Logistics = Logistics_Dummy_Send(','.join(tids), token)
                    Logistics.validate_tid()

    def notification(self, order_number, rate):
        info = db.query(report_info).filter_by(order_number=order_number).first()
        user_info = db.query(User).filter_by(id=info.user).first()
        if user_info.gzh_open_id != '':
            notification = Notification()
            notification_title = info.title[0:8] + '...'
            notification_rate = rate + '%'
            notification.ReportCompletedNotification(user_info.gzh_open_id, notification_title, info.create_datetime,
                                                     notification_rate)

    @shutdown_session
    def makeAigcReport(self, order_number):
        report = ExportAIGCReport(order_number)
        self.checkAIGC(order_number)
        base_info = self.base_info(order_number)
        self.create_barcode(report, order_number)
        self.create_pdf_html(report, base_info, order_number)
        self.logistics(order_number)


def run():
    r = RedisClient()
    while True:
        order_number = r.get_aigc_order_number
        try:
            if order_number:
                bot = MakeAIGCReport()
                bot.makeAigcReport(order_number)
            else:
                time.sleep(3)
        except Exception as e:
            print(e)
            time.sleep(3)


def run_test():
    order_number = '881715607805971'
    bot = MakeAIGCReport()
    bot.makeAigcReport(order_number)


if __name__ == '__main__':
    run()
